package com.mysen.sso.util;

import javax.servlet.http.HttpServletResponse;

import org.mybatis.spring.MyBatisSystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MissingRequestCookieException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.mysen.exception.MaikeServiceException;
import com.mysen.model.Response;

@ControllerAdvice
@ResponseBody
public class WebExceptionHandle {
	private static final Logger LOGGER = LoggerFactory.getLogger(WebExceptionHandle.class);
    
	@Autowired
	private HttpServletResponse response;
	
    /**
     * 500 - Internal Server Error
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public Response<?> handleException(Exception e) {
    	Response<?> resp = new Response<>();
        if (e instanceof MaikeServiceException){
			LOGGER.error("MaikeServiceException", e);
			resp.setErrorMsg(e.getMessage());
	        response.setStatus(401);
			resp.setSuccess(false);
        }else if(e instanceof MyBatisSystemException){
	        LOGGER.error("MyBatisSystemException:{}", e.getMessage());
			resp.setErrorMsg(Response.MSG_DB_ERROR);
	        response.setStatus(500);
			resp.setSuccess(false);
        } else if (e instanceof MissingServletRequestParameterException){
	        LOGGER.error("MissingServletRequestParameterException:{}", e.getMessage());
			resp.setErrorMsg(Response.MSG_PARAM_ERROR);
	        response.setStatus(403);
			resp.setSuccess(false);
        } else if (e instanceof MissingRequestCookieException){
	        LOGGER.error("MissingRequestCookieException:{}", e.getMessage());
	        response.setStatus(401);
			resp.setErrorMsg(Response.MSG_UNLOGIN);
			resp.setSuccess(false);
        } else {
	        LOGGER.error("unkown error:", e);
			resp.setErrorMsg(Response.MSG_SERVICE_ERROR);
	        response.setStatus(500);
			resp.setSuccess(false);
        }
		return resp;
    }
}